import json
import os

import pandas as pd
from copy import deepcopy
from my_json import load_json

basic_path = str(os.path.dirname(__file__)) + "\\"
sim_path = basic_path + "sim\\school_grade_sim.csv"
grade_path = basic_path + "sim\\school_grade.csv"
school_detail_path = basic_path + "..\\school_detail\\school_detail.json"

sim_save_path = basic_path + "sim\\sim_index.csv"
major_save_path = basic_path + "sim\\major_index.csv"


def init_school():
    t = []
    school_detail = load_json(school_detail_path)
    columns = ["school_name", "school_province_name", "is_dual_class", "is_985", "is_211"]
    for k, v in school_detail.items():
        school_name = v["name"]
        school_province_name = v["province_name"]
        is_dual_class = 0
        is_985 = 0
        is_211 = 0
        if v["dual_class_name"] == "双一流":
            is_dual_class = 1
        if v["f985"] == "1":
            is_985 = 1
        if v["f211"] == "1":
            is_211 = 1
        d = [school_name, school_province_name, is_dual_class, is_985, is_211]
        t.append(d)
    return pd.DataFrame(t, columns=columns)


school_detail = init_school()


def subject_sort(subjects):
    if len(subjects) <= 1:
        return subjects
    order = {"物理": 1, "历史": 2, "化学": 3, "政治": 4, "生物": 5, "地理": 6, "技术": 7}
    return sorted(subjects, key=lambda x: order.get(x, float('inf')))


def load_require(require):
    require = json.loads(require)
    n = require["n"]
    r = subject_sort(require["r"])
    o = subject_sort(require["o"])
    d = []
    if n > 0:
        if n == 1:
            o = [[subject] for subject in o]
        elif n == 2:
            o = [[o[0], o[1]], [o[1], o[2]], [o[0], o[2]]]
        for i in range(len(o)):
            r1 = deepcopy(r)
            r1.extend(o[i])
            r1 = subject_sort(r1)
            while len(r1) < 3:
                r1.append("")
            d.append(r1)
    else:
        while len(r) < 3:
            r.append("")
        d.append(r)
    return d


def index_sim():
    columns = ["province_name", "school_name", "min_rank", "choose1", "choose2", "choose3",
               "school_province_name", "is_dual_class", "is_985", "is_211"]
    sim = pd.read_csv(sim_path, encoding="utf-8-sig")
    sim = sim[(sim["type_name"] == "普通类")]
    sim = sim.groupby(["province_name", "school_name", "require_json"])[["min_rank"]].mean().reset_index()
    df = []
    columns1 = ["province_name", "school_name", "min_rank", "choose1", "choose2", "choose3"]
    for i in sim.iterrows():
        j = i[1]
        province_name = j["province_name"]
        school_name = j["school_name"]
        min_rank = j["min_rank"]
        require = load_require(j["require_json"])
        for j in require:
            df.append([province_name, school_name, min_rank, j[0], j[1], j[2]])
    df = pd.DataFrame(df, columns=columns1)
    df = df.groupby(["province_name", "school_name", "choose1", "choose2", "choose3"])[
        ["min_rank"]].mean().reset_index()
    df = pd.merge(df, school_detail, how="left", on="school_name")
    print("sort")
    df.sort_values(by=["province_name", "school_name", "min_rank", "choose1", "choose2", "choose3"], ignore_index=True,
                   inplace=True)
    df.to_csv(sim_save_path, index=False, encoding="utf_8_sig")


def index_major():
    columns = ["province_name", "school_name", "major_class", "major_name", "has_plan", "min_rank",
               "choose1", "choose2", "choose3", "school_province_name", "is_dual_class", "is_985", "is_211"]
    year = "2023"
    grade = pd.read_csv(grade_path, encoding="utf-8-sig")
    grade = grade[(grade["type_name"] == "普通类")]
    grade_plan = grade[(grade["is_plan"] == 1) & (grade["year"] == year)]
    grade = grade[(grade["is_grade"] == 1)]
    grade = grade.groupby(["province_name", "school_name", "level2_name", "major_name", "require_json"]) \
        .agg({"min_rank": "mean"}).reset_index()
    df = []
    columns1 = ["province_name", "school_name", "major_class", "major_name", "has_plan", "min_rank",
               "choose1", "choose2", "choose3"]
    for i in grade.iterrows():
        j = i[1]
        province_name = j["province_name"]
        school_name = j["school_name"]
        major_class = j["level2_name"]
        major_name = j["major_name"]
        has_plan = 0
        if j["major_name"] in grade_plan["major_name"]:
            has_plan = 1
        min_rank = j["min_rank"]
        require = load_require(j["require_json"])
        for j in require:
            df.append([province_name, school_name, major_class, major_name, has_plan, min_rank, j[0], j[1], j[2]])
    df = pd.DataFrame(df, columns=columns1)
    df = df.groupby(["province_name", "school_name", "major_class", "major_name", "has_plan", "choose1",
                     "choose2", "choose3"])[["min_rank"]].mean().reset_index()
    df = pd.merge(df, school_detail, how="left", on="school_name")
    print("sort")
    df.sort_values(by=["province_name", "school_name", "major_class", "major_name", "min_rank", "choose1", "choose2",
                       "choose3"], ignore_index=True, inplace=True)
    df.to_csv(major_save_path, index=False, encoding="utf_8_sig")


index_sim()
# index_major()
